﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;

namespace XFControls.XFPanels
{
    public partial class XFPanelAlphabetBar : Panel
    {
        public delegate void LetterChangedEventHandler(char newLetter);
        public event LetterChangedEventHandler LetterChanged;

        private char selLetter;
        private char[] _letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
        new public int Width { get; set; }
        public Color BoarderColor { get; set; }
        public int xOffset { get; set; }

        public XFPanelAlphabetBar()
        {
            InitializeComponent();
            Width = 50;
            selLetter = ' ';
            BoarderColor = Color.Black;
        }

        public void PainAlphaBar(Graphics g)
        {
            using (SolidBrush b = new SolidBrush(Color.DarkGray))
                g.FillRectangle(b, xOffset - Width, 0, Width, Height);

            if (selLetter != ' ')
            {
                int x = Screen.PrimaryScreen.WorkingArea.Width / 2;
                int y = 200;

                using (Font f = new Font(FontFamily.GenericMonospace, 20, FontStyle.Bold))
                {
                    var tLength = g.MeasureString(selLetter.ToString(), f);

                    x -= (int)tLength.Width / 2;
                    y -= (int)tLength.Height / 2;
                    using (SolidBrush b = new SolidBrush(Color.Black))
                        g.DrawString(selLetter.ToString(), f, b, x, y);
                }
            }
        }

        public void PanelMouseDown(MouseEventArgs e)
        {
            double itmHeight = (double)Height / (double)_letters.Length;

            int letterIndex = 0;
            for (; (letterIndex + 1) * itmHeight < e.Y; letterIndex++) { }

            selLetter = _letters[letterIndex];

            if (Parent != null)
                Parent.Invalidate();
        }

        public void PanelMouseMove(MouseEventArgs e)
        {
            double itmHeight = (double)Height / (double)_letters.Length;

            int letterIndex = 0;
            for (; (letterIndex + 1) * itmHeight < e.Y; letterIndex++) { }

            if (letterIndex > _letters.Length)
                selLetter = _letters.Last();
            else
                selLetter = _letters[letterIndex];

            if (Parent != null)
                Parent.Invalidate();
        }

        public void PanelMouseUp(MouseEventArgs e)
        {
            if (LetterChanged != null)
            {
                LetterChanged(selLetter);
            }
            selLetter = ' ';

            if (Parent != null)
                Parent.Invalidate();
        }
    }
}
